<template>
  <div class="countdown-container">
    <div class="countdown-item">
      <div class="countdown-value">{{ days }}</div>
      <div class="countdown-label">天</div>
    </div>
    <div class="countdown-item">
      <div class="countdown-value">{{ hours }}</div>
      <div class="countdown-label">小时</div>
    </div>
    <div class="countdown-item">
      <div class="countdown-value">{{ minutes }}</div>
      <div class="countdown-label">分</div>
    </div>
    <div class="countdown-item">
      <div class="countdown-value">{{ seconds }}</div>
      <div class="countdown-label">秒</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';

// 定义props
const props = defineProps({
  // 目标时间，可以是日期字符串或时间戳
  targetTime: {
    type: [String, Number, Date],
    required: true
  },
  // 倒计时结束后的回调函数
  onFinish: {
    type: Function,
    default: () => {}
  }
});

// 剩余时间（毫秒）
const remainingTime = ref(0);

// 计算剩余的天、小时、分钟和秒
const days = computed(() => {
  return Math.floor(remainingTime.value / (1000 * 60 * 60 * 24)).toString().padStart(2, '0');
});

const hours = computed(() => {
  return Math.floor((remainingTime.value % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, '0');
});

const minutes = computed(() => {
  return Math.floor((remainingTime.value % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
});

const seconds = computed(() => {
  return Math.floor((remainingTime.value % (1000 * 60)) / 1000).toString().padStart(2, '0');
});

// 更新剩余时间
const updateRemainingTime = () => {
  const now = new Date().getTime();
  const target = new Date(props.targetTime).getTime();

  // 计算剩余时间
  const diff = target - now;

  // 如果倒计时结束
  if (diff <= 0) {
    remainingTime.value = 0;
    props.onFinish();
    // 清除定时器
    if (timer) {
      clearInterval(timer);
    }
  } else {
    remainingTime.value = diff;
  }
};

// 定时器
let timer = null;

// 组件挂载时启动倒计时
onMounted(() => {
  // 初始化剩余时间
  updateRemainingTime();

  // 每秒更新一次
  timer = setInterval(() => {
    updateRemainingTime();
  }, 1000);
});

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
});
</script>

<style scoped>
.countdown-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 28px;
  font-family: 'PingFang-SC-Regular', Arial, sans-serif;
}

.countdown-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #fff;
  border-radius: 24px;
  padding: 20px 70px;
  min-width: 60px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.countdown-value {
  font-size: 60px;
  color: #5F3789;
  line-height: 1.1;
}

.countdown-label {
  font-size: 20px;
  color: #666;
  margin-top: 10px;
}
</style>
